package Helper;

import android.provider.ContactsContract;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * Created by 王彦鹏 on 2018-09-07.
 */
public class AFile {
    private String filePath,fileName;

    private boolean makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                return file.mkdirs();
            }
            else
            {
                return true;
            }
        } catch (Exception e) {
            Log.write("error:", e+"");
            return false;
        }
    }

    public AFile(String path, String fName,boolean createFlag){
        filePath=path;
        fileName=fName;
        File file = new File(path,fName);
        try {
            if (!file.exists()) {
                if (makeRootDirectory(path)) {
                    if (file.createNewFile()) {

                    }
                }
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void Write(byte[] bytes,int offset,int len) throws IOException {
        File file = new File(filePath,fileName);
        FileOutputStream wfos=new FileOutputStream(file);
        wfos.write(bytes,offset,len);
        wfos.close();
    }
    public void Write(byte[] bytes) throws IOException {
        File file = new File(filePath,fileName);
        FileOutputStream wfos=new FileOutputStream(file);
        wfos.write(bytes);
        wfos.close();
    }
    public byte[] Read(int offset,int len) throws IOException {
        File file = new File(filePath,fileName);
        FileInputStream rfos=new FileInputStream(file);
        byte[] buf=new byte[len];
        int res= rfos.read(buf,offset,len);
        rfos.close();
        return buf;
    }
    public byte[] Read() throws IOException {
        File file = new File(filePath,fileName);
        FileInputStream rfos=new FileInputStream(file);
        byte[] buf=new byte[(int)file.length()];
        int res= rfos.read(buf);
        rfos.close();
        return buf;
    }
}
